<template>
  <div class="file-selector">
    <div @click="showImgSelector(i)" v-for="i in maxSelectNumber" class="upload-img-wrap">
      <div v-if="i > values.length">
        <span class="upload-trigger"><span>+</span></span>
        <p class="upload-tips"></p>
      </div>
      <div v-if="i <= values.length" class="upload-img">
        <span @click.stop="handleDelImg(i)" class="remove">×</span>
        <span class="img-edit"><span class="sku-item__text">替换</span></span>
        <img :src="values[i-1]"/>
      </div>
    </div>

    <el-dialog
      title="选择文件"
      width="800px"
      append-to-body
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="dialogVisible"
    >
      <div class="file-selector-content">
        <div class="file-breadcrumb">
          <!--目录-->
          <div v-show="catalogArray.length > 1" class="file-catalog" style="width: 110px;">
            <el-breadcrumb separator="|" style="display: inline">
              <el-breadcrumb-item><span @click="returnPrev()" class="a-link">返回上一级</span></el-breadcrumb-item>
              <el-breadcrumb-item></el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="file-catalog" style="width: 500px;">
            <el-breadcrumb separator-class="el-icon-arrow-right" style="display: inline">
              <el-breadcrumb-item v-for="(item,index) in catalogArray" :key="item.id">
                <span v-if="index === catalogArray.length-1">{{item.fileName}}</span>
                <span v-else @click="skipFolder(index)" class="a-link">{{item.fileName}}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
        </div>
        <el-scrollbar class="file-selector-list" v-loading="loading">
          <ul style="padding: 0;">
            <template v-for="item in fileList">
              <li class="file-list-item cursor"
                  :style="currentFile.id === item.id?'border: 2px solid #409EFF;':''"
              >
                <div>

                  <img v-if="item.fileType !== 'folder'"
                       @click="chooseImg(item)"
                       :src="getFileType(item)"
                       class="file-item-thumbnail">
                  <img v-if="item.fileType === 'folder'"
                       :src="getFileType(item)"
                       @click="openFolder(item)"
                       class="file-item-thumbnail cursor">
                </div>
                <div class="file-item-name">{{item.fileName}}</div>
              </li>
            </template>
          </ul>
          <span v-show="fileList.length===0" style="position: absolute;top: 100px;left: 250px;">暂无数据</span>
        </el-scrollbar>
        <!--分页-->
        <el-pagination
          style="margin: 20px;float: left;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-size="searchParam.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[15,30,50,100]"
          :total="total">
        </el-pagination>
      </div>
      <span slot="title">
        <div  class="inline-block">
               <el-button
                 @click="addFolder"
                 icon="el-icon-plus"
                 size="small"
               >
                 新建文件夹
               </el-button>

               <es-upload-file
                 accept="image/*"
                 :data="{parentId:searchParam.parentId}"
                 action="/admin/file/upload"
                 @uploadSuccess="uploadSuccess"
                 btn-size="small"
               ></es-upload-file>
          <!--<el-button type="primary" icon="el-icon-download" size="small">下载</el-button>-->

        </div>
        <div class="inline-block float-right">
             <el-input v-model="searchParam.fileNameVague"
                       prefix-icon="el-icon-search"
                       style="width: 200px;"
                       placeholder="搜索您的文件"
                       clearable
             >
           </el-input>
           <el-button type="primary" size="small" icon="el-icon-search" @click="searchForm">查询</el-button>
        </div>

      </span>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectFile">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import config from '../../config'
  import {getImgList, addFolder} from '../../api/file/fileApi'

  export default {
    name: 'es-img-selector',
    props: {
      value: String,//图片回显，多张照片用逗号隔开
      maxSelectNumber: {//最多可选数量
        type: Number,
        default: 1
      },
      action: String,//上传地址
    },
    model:{
      event:'changeValue'
    },
    data: function () {
      return {
        searchParam: {//表格数据请求参数
          fileNameVague: '',
          parentId: 0,
          page: 1,
          limit: 15
        },
        dialogVisible: this.show,
        uploadUrl: config.uploadUrl,
        loading: false,
        values: [],//图片回显
        fileList: [],//文件列表
        currentFileIndex: 0,//当前回显图片下标
        total: 0,
        catalogArray: [{id: 0, fileName: '全部文件'}],
        currentFile: {},
        checkboxList: [],
      }
    },
    mounted () {
      this.values = !!this.value ? this.value.split(',') : [];
    },
    watch: {
      value:function (val) {
        this.values = !!val ? val.split(',') : []
      },
      values:function (val) {
        this.$emit("changeValue",val.join(","));
      }
    },
    methods: {
      //打开文件选择器
      showImgSelector (i) {
        this.currentFileIndex = i - 1
        this.dialogVisible = true
        this.getTableData()
      },
      chooseImg(file){
        this.currentFile=file;
      },
      //删除图片
      handleDelImg (index) {
        this.values.splice(index - 1, 1);
        this.$emit("changeValue",this.values.join(","));
      },
      //新增文件夹
      addFolder (parentId) {
        let _this = this
        parentId = typeof parentId === 'string' ? parentId : _this.searchParam.parentId
        _this.$prompt('请输入文件夹名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[\S\s]{1,200}$/,
          inputErrorMessage: '请输入1-200个字符的名称'
        }).then(({value}) => {
          if (!value) {
            _this.$message.error('请输入1-200个字符的名称')
            return false
          }
          addFolder({parentId: parentId, fileName: value}).then(res => {
            if (res.code === 200) {
              //刷新表格数据
              _this.getTableData()
              _this.$message.success('新增成功!')
            } else {
              _this.$message.error(res.msg)
            }
          })
        })

      },
      uploadSuccess (res) {
        this.getTableData()
      },
      selectFile () {
        if (Object.keys(this.currentFile).length === 0) {
          this.$message.warning('未选中文件')
          return false
        }
        this.values[this.currentFileIndex]=this.currentFile.fileUrl;
        this.dialogVisible = false
        this.$emit("changeValue",this.values.join(","));
      },
      //查询表格
      searchForm () {
        this.searchParam.page = 1
        //获取数据
        this.getTableData()
      },
      //获取数据
      getTableData () {
        let _this = this
        _this.loading = true
        getImgList(_this.searchParam).then((res) => {
          if (res.code === 200) {
            _this.fileList = res.data
            _this.total = res.total
          } else {
            this.$message.error(res.msg)
          }
          _this.loading = false
        })
      },
      //打开文件夹
      openFolder (parent) {
        this.searchParam.parentId = parent.id
        //刷新表格数据
        this.getTableData()
        this.catalogArray.push({id: parent.id, fileName: parent.fileName})
      },
      //返回上一级
      returnPrev () {
        this.skipFolder(this.catalogArray.length - 2)
      },
      //文件夹目录跳转
      skipFolder (index) {
        this.catalogArray = this.catalogArray.slice(0, index + 1);
        this.searchParam.parentId = this.catalogArray[this.catalogArray.length - 1].id
        //刷新表格数据
        this.getTableData()
      },
      getFileType (row) {
        if (row.fileType === 'pic') {
          return row.fileUrl
        }
        return `/static/img/file/${row.fileType}.png`
      },
      handleSizeChange (limit) {
        this.searchParam.limit = limit
        //获取数据
        this.getTableData()
      },
      handleCurrentChange (page) {
        this.searchParam.page = page
        //获取数据
        this.getTableData()
      },
    }
  }
</script>

<style>

</style>
<style scoped>
  .upload-img-wrap {
    cursor: pointer;
    position: relative;
    display: inline-block;
    vertical-align: middle;
    text-align: center;
    padding: 2px;
    margin-left: 10px;
    width: 90px;
    height: 90px;
    background: #fff;
    border-radius: 4px;
    border: 1px solid #e5e5e5;
  }

  .upload-img-wrap .upload-img img {
    position: relative;
    width: 90px;
    height: 90px;
  }

  .upload-img-wrap .upload-trigger {
    width: 84px;
    height: 84px;
    line-height: 84px;
    background: #fff;
    font-size: 30px;
    color: #e5e5e5;
    border: 0;
  }

  .upload-img-wrap .img-edit {
    display: none;
    position: absolute;
    bottom: 0;
    left: 0;
    line-height: 25px;
    z-index: 1;
    width: 89px;
    margin-left: 2px;
    margin-bottom: 2px;
    color: #fff;
    border-right: 2px solid transparent;
    opacity: .5;
    background: #333;
  }

  .upload-img:hover > .img-edit {
    display: block !important;
  }

  .sku-item__text {
    display: block;
    width: 74px;
    margin: 0 auto;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .upload-img .remove {
    top: -6px;
    right: -6px;
  }

  .upload-img:hover > .remove {
    display: block;
  }

  .remove {
    top: 12px;
    right: 10px;
    display: none;
    position: absolute;
    z-index: 2;
    width: 18px;
    height: 18px;
    font-size: 14px;
    line-height: 16px;
    color: #fff;
    text-align: center;
    background: rgba(0, 0, 0, .3);
    border-radius: 50%;
  }
</style>
